package com.system.config;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.system.anno.PayTemplate;
import com.system.base.pay.AbstractPayTemplate;
import com.system.handler.ServiceException;

@Component
public class PayTemplateContext implements ApplicationContextAware {

	@Resource
	private ApplicationContext applicationContext;

	private static final Map<String, Class<?>> templateMap = new HashMap<>(16);

	public AbstractPayTemplate getTemplateInstance(String payType) {
		Class<?> clazz = templateMap.get(payType);
		if (clazz == null) {
			throw ServiceException.bulid("暂不支持该支付方式！");
		}
		return (AbstractPayTemplate) this.applicationContext.getBean(clazz);
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
		// 遍历带有PayTemplate注释的类
		Map<String, Object> beans = applicationContext.getBeansWithAnnotation(PayTemplate.class);
		if (beans != null && beans.size() > 0) {
			for (Object serviceBean : beans.values()) {
				String payType = serviceBean.getClass().getAnnotation(PayTemplate.class).code();
				templateMap.put(payType, serviceBean.getClass());
			}
		}
	}
	
}
